using System;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

namespace VladanStrigoNET.Samples.Blogged
{
    public class IoC
    {
        private static IWindsorContainer _container;
        private static object _containerKey = new object();

        public static void Initialize()
        {
            Initialize("");
        }
        public static void Initialize(string configFilePath)
        {
            Initialize(_CreateNewWindsorContainer(configFilePath));
        }
        public static void Initialize(IWindsorContainer windsorContainer)
        {
            _container = windsorContainer;
        }
        public static T Resolve<T>()
        {
            return Container.Resolve<T>();
        }
        public static T Resolve<T>(string name)
        {
            return Container.Resolve<T>(name);
        }
        public static object Resolve(Type typeToResolve)
        {
            return Container.Resolve(typeToResolve);
        }
        public static IWindsorContainer Container
        {
            get
            {
                _EnsureContainerIsInitialized(_container);

                return _container;
            }
        }
        public static bool IsInitialized
        {
            get { return _container != null; }
        }
        public static void Reset()
        {
            Reset(_container);
        }
        public static void Reset(IWindsorContainer containerToReset)
        {
            if (containerToReset == null) return;

            _ResetContainerByReference(_container, containerToReset);
        }



        private static IWindsorContainer _CreateNewWindsorContainer(string configFilePath)
        {
            IWindsorContainer container = null;

            if (!String.IsNullOrEmpty(configFilePath)) container = new WindsorContainer(new XmlInterpreter(configFilePath));

            if (container == null) container = new WindsorContainer(new XmlInterpreter());


            return container;
        }
        private static void _EnsureContainerIsInitialized(IWindsorContainer container)
        {
            if (container == null) throw new InvalidOperationException("The container has not been initialized!");
        }

        private static void _ResetContainerByReference(IWindsorContainer containerReference, IWindsorContainer containerToReset)
        {
            if (ReferenceEquals(containerReference, containerToReset)) containerReference = null;
        }

    }
}
